import React from 'react';
import RouterContext from './context';
import {pathToRegexp,Key} from 'path-to-regexp';

interface Props {
    // children: Array<JSX.Element>;
    children: Array<React.ReactElement>; //{type,props,key}
}
export default class extends React.Component<Props>{
    static contextType = RouterContext;
    render(){
      const pathname = this.context.location.pathname;
      if(this.props.children){
        const children: Array<React.ReactNode> = Array.isArray(this.props.children) ? this.props.children : [this.props.children];
        for(let i=0;i<children.length;++i) {
          const child: React.ReactElement = this.props.children[i];
          const {path = '/', exact = false, component: RouteComponent} = child.props;
          const keys: Array<Key> = [];
          const regexp = pathToRegexp(path, keys, {end: exact});
          if(pathname.match(regexp)){
            return child;
          }
        }
      }
      return null;
    }
}
